package yourauthor.workcomparator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ross
 */
public class CompareByPunctuationRatio implements WorkComparator {
    
    InputStream work1;
    InputStream work2;
    
    public CompareByPunctuationRatio(InputStream work1, InputStream work2) {
        this.work1 = work1;
        this.work2 = work2;
    }
    
    public boolean compareWorks() throws FileNotFoundException {
        PunctuationCount punctuationCountForWork1 = getPunctuationCountForWork(work1);
        PunctuationCount punctuationCountForWork2 = getPunctuationCountForWork(work2);
        return punctuationCountForWork1.compareTo(punctuationCountForWork2);
    }

    private PunctuationCount getPunctuationCountForWork(InputStream workInputStream) throws FileNotFoundException {
        PunctuationCount pc = new PunctuationCount();
        byte[] b = new byte[1024];
        int read = 0;
        String textBuffer = "";
        try {
            while ( (read = workInputStream.read(b)) != -1 ) {
                byte[] bytesToAdd = Arrays.copyOfRange(b, 0, read);
                textBuffer += new String(bytesToAdd);
                parsePunctuationFromStringBuffer(textBuffer, pc);
            }
        } catch (IOException ex) {
            Logger.getLogger(CompareByPunctuationRatio.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        //Check if any characters are leftover from buffer
        parsePunctuationFromStringBuffer(textBuffer, pc);
        return pc;
    }

    private void parsePunctuationFromStringBuffer(String textBuffer, PunctuationCount pc) {
        for ( int i = 0; i < textBuffer.length(); i++ ) {
            switch (textBuffer.charAt(i)) {
                case '.':pc.periods++;break;
                case ',':pc.commas++;break;
                case '?':pc.questionMarks++;break;
            }
        }
    }
    
    private class PunctuationCount {
        
        public int questionMarks = 0;
        public int commas = 0;
        public int periods = 0;
        
        public double questionMarkRatio() {
            return (double)((questionMarks*100)/(questionMarks+commas+periods))/100;
        }
        
        public double commaRatio() {
            return (double)((commas*100)/(questionMarks+commas+periods))/100;
        }
        
        public boolean compareTo(PunctuationCount pc) {
            if ( commaRatio()-.1 < pc.commaRatio() && commaRatio()+.1 > pc.commaRatio() ) {
                if ( questionMarkRatio()-.1 < pc.questionMarkRatio() && questionMarkRatio()+.1 > pc.questionMarkRatio() ) {
                    return true;
                }
            }
            return false;
        }
        
    }
}
